<template>
    <div class="add-product-modal-wrapper">
        <el-dialog :model-value="props.value" :title="dialog.title" :width="dialog.width" destroy-on-close>
            <Block>
                <DataGrid
                    :auto-load="autoLoad"
                    ref="dataGridRef"
                    @selection-change="handleSelectionChange"
                    showSelection
                >
                    <template #toolbar-search>
                        <div class="query-from-box">
                            <el-form>
                                <el-form-item>
                                    <el-input v-model="queryData.productKey" placeholder="产品名称/标识符" clearable />
                                </el-form-item>
                                <el-form-item>
                                    <el-tree-select
                                        placeholder="产品标签"
                                        v-model="queryData.labels"
                                        :data="labelTree"
                                        :props="defaultProps"
                                        multiple
                                        collapse-tags
                                        collapse-tags-tooltip
                                        check-strictly
                                        :render-after-expand="false"
                                        show-checkbox
                                        clearable
                                        node-key="labelNo"
                                    />
                                </el-form-item>
                                <el-form-item>
                                    <el-input
                                        v-model="queryData.objectDisplayName"
                                        placeholder="产品模型名称"
                                        clearable
                                    />
                                </el-form-item>
                                <el-form-item>
                                    <el-select placeholder="集成状态" v-model="queryData.integrationEnable" clearable>
                                        <el-option
                                            v-for="(value, key) in IntegrationEnable"
                                            :label="value"
                                            :key="key"
                                            :value="key"
                                        />
                                    </el-select>
                                </el-form-item>
                            </el-form>
                        </div>
                    </template>
                    <el-table-column type="index" label="序号" width="60" align="center" fixed />
                    <el-table-column label="产品名称" width="300" fixed show-overflow-tooltip>
                        <template #default="scope">
                            <el-button link type="primary" @click="onGoDetail(scope.row)">
                                {{ scope.row.productName }}
                            </el-button>
                        </template>
                    </el-table-column>
                    <el-table-column prop="productNo" label="标识符" show-overflow-tooltip />
                    <el-table-column label="产品标签" show-overflow-tooltip>
                        <template #default="scope">
                            {{ scope.row.labelNames ? scope.row.labelNames.join('；') : '' }}
                        </template>
                    </el-table-column>
                    <el-table-column label="节点类型" width="95">
                        <template #default="scope">
                            <div class="table-item-tag">
                                <el-tag
                                    :type="
                                        scope.row.productType == 'DIRECT'
                                            ? 'success'
                                            : scope.row.productType == 'GATEWAY'
                                              ? 'primary'
                                              : 'warning'
                                    "
                                    >{{ ProductType[scope.row.productType] }}</el-tag
                                >
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="objectDisplayName" label="产品模型" show-overflow-tooltip />
                    <el-table-column label="集成状态" width="80">
                        <template #default="scope">
                            <span class="table-item-status" :status="IntegrationEnable[scope.row.integrationEnable]">
                                {{ IntegrationEnable[scope.row.integrationEnable] }}
                            </span>
                        </template>
                    </el-table-column>
                </DataGrid>
            </Block>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="props.close">取消</el-button>
                    <el-button
                        type="primary"
                        @click="submitForm"
                        :loading="loading"
                        :disabled="tableSelectId && tableSelectId.length ? false : true"
                        >确定</el-button
                    >
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import { messageIntegrationService, runLabelService } from '@great/services';
import { reactive, ref } from 'vue';
import type { PopupBoxProps } from '@great/utils';
import { ProductType } from '@/utils/constant';
import { useRequest } from 'vue-request';
import { useRouter } from 'vue-router';
import { checkPermi } from '@/utils/ruoyi';
import { DataGrid, Block, type DataGridInstance } from '@great/components';

const router = useRouter();
interface IProps extends PopupBoxProps {
    messageDetail: Record<string, any>;
    callBack?: () => Promise<void>;
}
const props = defineProps<IProps>();

interface Dialog {
    title: string;
    width: number;
    detail?: Record<string, any>;
}
const dialog = reactive<Dialog>({
    title: '选择产品',
    width: 1200,
    detail: undefined
});

enum IntegrationEnable {
    true = '启用',
    false = '停用'
}
// 查询条件
const queryData = ref({
    productKey: '',
    labels: '',
    objectDisplayName: '',
    integrationEnable: ''
});
const defaultProps = {
    children: 'childLabel',
    label: 'labelName',
    value: 'labelNo'
};
const labelTree = ref();
const dataGridRef = useTemplateRef<DataGridInstance>('dataGridRef');
const autoLoad = reactive({
    debounce: true,
    reloadDeps: [queryData],
    onLoad: async (current, size) => {
        const res = await messageIntegrationService.getAddProductPage(
            {
                current,
                size,
                ...queryData.value
            },
            props.messageDetail.messageNo
        );
        return { data: res.data.records, total: res.data.total };
    }
});
// 表格勾选数据
const tableSelect = ref<unknown[]>([]);
const tableSelectId = ref<string[]>([]);
// 表格勾选
const handleSelectionChange = (val: unknown[]) => {
    tableSelect.value = val;
    tableSelectId.value = [];
    val.forEach((item: any) => {
        tableSelectId.value.push(item.productNo);
    });
};
// 查看详情
const onGoDetail = (row: { id: string }) => {
    if (checkPermi(['iot:product:detail'])) {
        closeDialog();
        router.push({
            name: 'IoT-product-detail',
            params: {
                id: row?.id
            }
        });
    }
};

// 提交接口请求
const { run, loading } = useRequest(
    () => {
        return messageIntegrationService.addProduct(tableSelectId.value, props.messageDetail.messageNo);
    },
    {
        manual: true,
        onSuccess(res) {
            ElNotification({
                title: `添加成功！`,
                type: 'success'
            });
            closeDialog();
        }
    }
);

// 表单提交
const submitForm = () => {
    run();
};
//关闭弹框
const closeDialog = () => {
    props.close();
    props.callBack?.();
};
// 获取标签
const getLabelTree = async () => {
    if (labelTree.value && labelTree.value.length > 0) return;
    const res = await runLabelService.getLabelTree({ labelTypeNo: 'labelType-producctLabel' });
    labelTree.value = res.data;
};
getLabelTree();
</script>
<style scoped lang="scss">
.add-product-modal-wrapper {
    .query-from-box {
        display: flex;
        align-items: center;
        .el-form {
            display: flex;
            .el-form-item {
                margin-bottom: 0;
                width: 192px;
            }
            .el-form-item + .el-form-item {
                margin-left: 10px;
            }
        }
    }
    :deep(.data-grid) {
        .table-item-tag {
            display: flex;
        }
        .table-item-status {
            display: flex;
            align-items: center;
            &::before {
                content: '';
                width: 6px;
                height: 6px;
                display: inline-block;
                border-radius: 50%;
                margin-right: 5px;
            }
        }
        .table-item-status[status='停用'] {
            &::before {
                background-color: #909399;
            }
        }
        .table-item-status[status='启用'] {
            &::before {
                background-color: #67c23a;
            }
        }
    }
}
</style>
